import {Component, OnInit} from '@angular/core';
import {DatePipe} from '@angular/common';
import {NzMessageService} from 'ng-zorro-antd/message';
import {Router, ActivatedRoute, NavigationExtras} from '@angular/router';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {CommodityBrandService} from './commodity-brand.service';
import {PermissionService} from '../../../../../service/permission.service';

@Component({
  selector: 'app-commodity-brand',
  templateUrl: './commodity-brand.component.html',
  styleUrls: ['./commodity-brand.component.scss'],
  providers: [DatePipe]
})
export class CommodityBrandComponent implements OnInit {

  // seachForm
  seachForms: any = {
    name: '' // 名称
  };
  // table
  tableForms: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0
  };
  // 表格data
  tableData: any = [];

  // 弹窗
  isVisible: boolean = false;
  // 弹窗form表单
  validateForm!: FormGroup;
  // isEdit 0：新增，1：编辑
  isEdit: number = 0;
  // updateItem编辑项数据
  updateItems: any = {};

  constructor(
    private datePipe: DatePipe,
    private message: NzMessageService,
    private router: Router,
    private fb: FormBuilder,
    private service: CommodityBrandService,
    public permission: PermissionService,
  ) {
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      name: [null, [Validators.required]],
      code: [null, [Validators.required]],
      sort: [null, [Validators.required]],
      nameEn: [null],
      isHide: [null, [Validators.required]],
      state: [null, [Validators.required]]
    });

    this.loadTable();
  }

  // loadDtable
  async loadTable() {
    try {
      let params = {
        ...this.seachForms,
        page: this.tableForms.page,
        pageSize: this.tableForms.pageSize
      };

      this.tableForms.tableLoading = true;
      const res: any = await this.service.queryTableData(params);
      this.tableForms.tableLoading = false;

      const {records, total}: any = res.data || [];
      this.tableData = records || [];
      this.tableForms.total = total || 0;
    } catch (error) {
      this.tableForms.tableLoading = false;

      this.tableData = [];
      this.tableForms.total = 0;
    }
  }

  // 搜索
  searchData() {
    this.tableForms.page = 1;
    this.loadTable();
  }

  // 重置table
  resetData() {
    this.seachForms.name = '';

    this.tableForms.page = 1;
    this.loadTable();
  }

  // 确认删除
  async deleteConfirm(id: any) {
    try {
      const res: any = await this.service.deleteCommodityBrandData(id);
      if (res.code == 0) {
        this.message.success('删除成功');

        this.tableForms.page = 1;
        this.loadTable();
      } else {
        this.message.error(res.message || '删除失败');
      }
    } catch (error) {
      this.message.error(error || '删除失败');
    }
  }

  // model弹出
  editItem(num: number, item?: any) {
    this.isEdit = num;
    this.updateItems = item;

    if (num == 1) {
      for (let key in this.validateForm.value) {
        this.validateForm.get(key)?.setValue((item[key] != null || item[key] != undefined) ? String(item[key]) : item[key]);
      }
    }
    this.isVisible = true;
  }

  // model确定
  async handleOk() {
    // this.isVisible = false;
    for (const key in this.validateForm.controls) {
      if (this.validateForm.controls.hasOwnProperty(key)) {
        this.validateForm.controls[key].markAsDirty();
        this.validateForm.controls[key].updateValueAndValidity();
      }
    }
    if (!this.validateForm.valid) {
      return;
    }
    for (let key in this.validateForm.value) {
      if (this.validateForm.value[key] == '' || this.validateForm.value[key] == null || this.validateForm.value[key] == undefined) {
        delete this.validateForm.value[key];
      }
    }

    let params = {
      ...this.validateForm.value
    };
    if (this.isEdit == 1) {
      params.id = this.updateItems.id;
    }
    // return
    if (this.isEdit == 0) {
      try {
        const res: any = await this.service.addCommodityBrandData(params);
        if (res.code == 0) {
          this.message.success('添加成功');
          this.isVisible = false;

          this.tableForms.page = 1;
          this.loadTable();
        } else {
          this.message.error(res.message || '添加失败');
        }
      } catch (error) {
        this.message.error(error || '添加失败');
      }
    } else if (this.isEdit == 1) {
      try {
        const res: any = await this.service.updateCommodityBrandData(params);
        if (res.code == 0) {
          this.message.success('编辑成功');
          this.isVisible = false;

          this.tableForms.page = 1;
          this.loadTable();
        } else {
          this.message.error(res.message || '编辑失败');
        }
      } catch (error) {
        this.message.error(error || '编辑失败');
      }
    }
  }

  // model取消
  handleCancel(): void {
    this.isVisible = false;
  }

  // 关闭模态框
  closeModel(event: any) {
    this.validateForm.reset();
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableForms.page = index;
    this.loadTable();
  }

  // 页数改变时回调
  onPageSizeChange(sizeNum: number) {
    this.tableForms.page = 1;
    this.tableForms.pageSize = sizeNum;

    this.loadTable();
  }
}
